<?php
class messageModel extends baseModel{
    protected $table = 'user_message';

    //列表
    public function message_list($limit,$where,$table)
    {
        if($table=='receive'){
            $table="JOIN {$this->model->pre}user_message_receive B ON A.mid = B.mid";
        }else if($table=='send'){
            $table="JOIN {$this->model->pre}user_message_send B ON A.mid = B.mid";
        }
        $sql="
        SELECT A.*,B.*
        FROM {$this->model->pre}user_message A 
        {$table}
        WHERE {$where}
        ORDER BY A.mid DESC
        LIMIT {$limit} 
        ";
        return $this->model->query($sql); 
    }

    //总数
    public function count($where,$table='receive') {
        if($table=='receive'){
            $table="JOIN {$this->model->pre}user_message_receive B ON A.mid = B.mid";
        }else if($table=='send'){
            $table="JOIN {$this->model->pre}user_message_send B ON A.mid = B.mid";
        }
        $sql="
        SELECT count(*) as num
        FROM {$this->model->pre}user_message A 
        {$table}
        WHERE {$where}
        ";
        $data=$this->model->query($sql);
        return $data[0]['num'];
    }


    //信息
    public function info($mid,$table='receive') {
        if($table=='receive'){
            $table="JOIN {$this->model->pre}user_message_receive B ON A.mid = B.mid";
        }else if($table=='send'){
            $table="JOIN {$this->model->pre}user_message_send B ON A.mid = B.mid";
        }
        $sql="
            SELECT A.*,B.*
            FROM {$this->model->pre}user_message A 
            {$table}
            WHERE A.mid={$mid} ORDER BY A.mid DESC LIMIT 1
            ";
        $data=$this->model->query($sql);
        return $data[0];
    }

    //添加
    public function add($data)
    {
        $this->table='user_message';
        $mid=$this->insert($data);
        
        $data2=array();
        $data2['uid']=$data['receive_uid'];
        $data2['send_uid']=$data['send_uid'];
        $data2['view']=0;
        $data2['mid']=$mid;
        $this->table='user_message_receive';
        $this->insert($data2);

        $data3=array();
        $data3['uid']=$data['send_uid'];
        $data3['receive_uid']=$data['receive_uid'];
        $data2['mid']=$mid;
        $this->table='user_message_send';
        $this->insert($data2);
        return $mid;
    }

    //已查看
    public function view($data)
    {
        $condition['uid']=intval($data['uid']);
        $condition['mid']=intval($data['mid']);
        $this->table='user_message_receive';
        return $this->update($condition,$data); 

    }

    //删除收件内容
    public function receive_del($mid,$uid)
    {
        $this->table='user_message_receive';
        $this->delete('mid='.$mid.' AND uid='.$uid);
        
    }

    //删除发件内容
    public function send_del($mid,$uid)
    {
        $this->table='user_message_send';
        $this->delete('mid='.$mid.' AND uid='.$uid);
        
    }

	
}